<template>
  <div class="doctor-list-container">
    <div class="fixed-header">
      <div class="page-header">
        <h3>医生管理</h3>
        <div class="search-group">
          <!-- 姓名搜索 -->
          <el-input
              v-model="searchParams.doctorName"
              placeholder="请输入姓名"
              clearable
              style="width: 200px"
          />

          <!-- 电话搜索 -->
          <el-input
              v-model="searchParams.phone"
              placeholder="请输入电话"
              clearable
              style="width: 200px"
          />

          <el-select
              v-model="searchParams.communityId"
              placeholder="选择社区"
              filterable
              remote
              :remote-method="filterCommunity"
              :loading="communityLoading"
              clearable
              style="width: 200px"
          >
            <el-option
                v-for="item in filteredCommunityList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>

          <!-- 搜索按钮 -->
          <el-button type="primary" @click="handleSearch">搜索</el-button>

          <!-- 重置按钮 -->
          <el-button @click="resetSearch">重置</el-button>
        </div>

        <!-- 添加子女按钮（保持右侧） -->
        <el-button type="primary" :icon="Plus" @click="handleAdd">添加医生</el-button>
      </div>
    </div>

    <el-table
        :data="doctorList"
        style="width: 100%"
        v-loading="loading"
        border
        stripe
        row-class-name="table-row"
    >
      <el-table-column prop="avatar" label="头像" align="center" width="100">
        <template #default="{ row }">
          <el-avatar :size="40" :src="row.avatar">
            <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" alt=""/>
          </el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="doctorName" label="姓名" align="center" min-width="120"/>
      <el-table-column prop="phone" label="手机号" align="center" min-width="150"/>
      <el-table-column label="负责社区" align="center" min-width="150">
        <template #default="{ row }">
          {{ row.communityId === 0 ? '无' : row.communityName }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="320" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" :icon="Edit" @click="handleEdit(row)">编辑</el-button>
          <el-button type="info" :icon="List" @click="handleViewTasks(row)">检查任务</el-button>
          <el-button type="danger" :icon="Delete" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 医生表单对话框 -->
    <doctor-form-dialog
        v-model="doctorFormVisible"
        :doctor="currentDoctor"
        :is-edit="dialogType === 'edit'"
        @success="handleSuccess"
    />

    <!-- 检查任务对话框 -->
    <doctor-check-task-dialog
        v-model="checkTaskVisible"
        :doctor="currentDoctor"
        :check-types="checkTypes"
        :doctor-list="doctorList"
        @success="handleSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, onActivated} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Plus, Edit, Delete, List} from '@element-plus/icons-vue'
import type {Doctor} from '@/types/doctor'
import type {Community} from '@/types/community'
import {getAllDoctors, deleteDoctor} from '@/api/doctor'
import {getAllCommunities} from '@/api/community'
import DoctorFormDialog from './components/DoctorFormDialog.vue'
import DoctorCheckTaskDialog from './components/DoctorCheckTaskDialog.vue'


interface DoctorWithCommunity extends Doctor {
  communityName?: string
}

const loading = ref(false)
const doctorList = ref<DoctorWithCommunity[]>([])
const communityList = ref<Community[]>([])
const doctorFormVisible = ref(false)
const checkTaskVisible = ref(false)
const currentDoctor = ref<DoctorWithCommunity>()
const dialogType = ref<'add' | 'edit'>('add')
const checkTypes = ref([])
// 其他变量不变
const communityLoading = ref(false)
const filteredCommunityList = ref<Community[]>([])


// 新增数据
const searchParams = ref({
  doctorName: '',
  phone: '',
  communityId: null
})


// 社区过滤方法
const filterCommunity = (query: string) => {
  if (query) {
    communityLoading.value = true
    setTimeout(() => {
      filteredCommunityList.value = communityList.value.filter(item => {
        return item.name.includes(query)
      })
      communityLoading.value = false
    }, 200)
  } else {
    filteredCommunityList.value = communityList.value
  }
}

// 修改 fetchCommunityList 方法
const fetchCommunityList = async () => {
  try {
    communityList.value = await getAllCommunities()
    filteredCommunityList.value = communityList.value
  } catch (error) {
    console.error('获取社区列表失败:', error)
  }
}

// 获取医生列表
const fetchDoctorList = async () => {
  loading.value = true
  try {
    const doctors = await getAllDoctors({
      doctorName: searchParams.value.doctorName,
      phone: searchParams.value.phone,
      communityId: searchParams.value.communityId
    })
    // 为每个医生添加社区名称
    doctorList.value = doctors.map((doctor: Doctor) => {
      const community = communityList.value.find((c: Community) => c.id === doctor.communityId)
      return {
        ...doctor,
        communityName: community ? community.name : '无'
      }
    })
  } catch (error) {
    console.error('获取医生列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索方法
const handleSearch = () => {
  fetchDoctorList();
}

// 重置搜索
const resetSearch = () => {
  searchParams.value = {
    doctorName: '',
    phone: '',
    communityId: null
  };
  fetchDoctorList();
}

// 添加医生
const handleAdd = () => {
  dialogType.value = 'add'
  currentDoctor.value = undefined
  doctorFormVisible.value = true
}

// 编辑医生
const handleEdit = (row: DoctorWithCommunity) => {
  dialogType.value = 'edit'
  currentDoctor.value = {...row} // 创建对象的副本，避免直接修改原对象
  doctorFormVisible.value = true
}

// 查看检查任务
const handleViewTasks = (row: DoctorWithCommunity) => {
  currentDoctor.value = row
  checkTaskVisible.value = true
}

// 删除医生
const handleDelete = async (row: DoctorWithCommunity) => {
  try {
    await ElMessageBox.confirm('删除后将无法恢复该医生的所有信息，包括检查任务，是否确认删除？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
      closeOnClickModal: false
    })
    await deleteDoctor({id: row.id})
    ElMessage.success('删除成功')
    await fetchDoctorList()
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消删除')
    }
  }
}

// 表单提交成功
const handleSuccess = () => {
  fetchDoctorList()
}

async function getData(){
  await fetchCommunityList()
  await fetchDoctorList()
}

onActivated(() => {
  getData()
})
</script>

<style scoped>
.doctor-list-container {
  display: flex;
  flex-direction: column;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  height: 95%;
}

.fixed-header {
  flex-shrink: 0;
  padding-bottom: 20px;
  background-color: #fff;
  z-index: 1;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
  color: #303133;
}

.search-group {
  display: flex;
  align-items: center;
  gap: 10px; /* 统一设置元素间间距 */
}

/* 统一输入框和按钮的宽度和间距 */
.search-group .el-input,
.search-group .el-select,
.search-group .el-button {
  margin: 0; /* 清除默认margin */
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa !important;
}

:deep(.el-table--border) {
  border: 1px solid #ebeef5;
}

:deep(.el-table--border th),
:deep(.el-table--border td) {
  border-right: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-button) {
  transition: all 0.3s;
}

:deep(.el-button.is-link) {
  height: 32px;
  padding: 0 12px;
  font-size: 14px;
}

:deep(.el-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.el-button.is-link.el-button--danger:hover) {
  background-color: #fef0f0;
}

:deep(.el-button.is-link.el-button--primary:hover) {
  background-color: #ecf5ff;
}

:deep(.el-button.is-link.el-button--info:hover) {
  background-color: #f4f4f5;
}

:deep(.el-avatar) {
  border: 2px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.el-table .cell) {
  display: flex;
  align-items: center;
  justify-content: center;
}

/* Dialog styles */
:deep(.el-dialog__header) {
  margin: 0;
  padding: 20px 30px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-dialog__body) {
  padding: 20px 30px;
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

:deep(.el-dialog__footer) {
  padding: 20px 30px;
  border-top: 1px solid #ebeef5;
}

:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

/* Button styles */
.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
  color: #fff;
  transition: all 0.3s;
}

.el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.el-button--danger {
  background-color: #f56c6c;
  border-color: #f56c6c;
  color: #fff;
  transition: all 0.3s;
}

.el-button--danger:hover {
  background-color: #f78989;
  border-color: #f78989;
}

.el-button--info {
  background-color: #909399;
  border-color: #909399;
  color: #fff;
  transition: all 0.3s;
}

.el-button--info:hover {
  background-color: #a6a9ad;
  border-color: #a6a9ad;
}
</style> 